# coding:utf-8
import pymongo
import datetime
import os
import time
from sqlalchemy import Column, Integer, String, DateTime, Numeric, create_engine, VARCHAR
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import sys
sys.path.append('..')
from db.ISqlHelper import ISqlHelper
from config import *

BaseModel = declarative_base()
class SearchRoomDetail(BaseModel):
    __tablename__ = 'SearchRoomDetail'
    name = Column(VARCHAR(100),default='主播名')
    data_momoid = Column(Integer, primary_key=True)
    number = Column(Integer,default=0)
    searc_count = Column(Integer,default=0)
    update_time = Column(DateTime,default=datetime.datetime.now)
    now_time = Column(DateTime(),default=datetime.datetime.now)


class MongoHelper(ISqlHelper):
    def __init__(self):
        self.client = pymongo.MongoClient(DB_CONNECT_STRING_MongoDB, connect=False)

    def init_db(self):
        self.db = self.client.momo
        self.srDB = self.db.SearchRoomDetail

    def drop_db(self):
        self.client.drop_database(self.db)

    def insert(self, value=None):
        if value:
            SearchRoomDetail = dict(name=value['name'], data_momoid=value['data_momoid'], 
            number=value['number'], searc_count=value['searc_count'],
                          update_time=value['update_time'])
            self.srDB.insert(SearchRoomDetail)

    def delete(self, conditions=None):
        if conditions:
            self.srDB.remove(conditions)
            return ('deleteNum', 'ok')
        else:
            return ('deleteNum', 'None')

    def update(self, conditions=None, value=None):
        # update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})
        if conditions and value:
            self.srDB.update(conditions, {"$set": value})
            return {'updateNum': 'ok'}
        else:
            return {'updateNum': 'fail'}

    def select(self, count=None, conditions=None):
        if count:
            count = int(count)
        else:
            count = 0

        items = self.srDB.find(conditions, limit=count)
        results = []
        for item in items:
            results.append(item)
        return results


if __name__ == '__main__':
    from db.MongoHelper import MongoHelper as SqlHelper
    sqlhelper = SqlHelper()
    sqlhelper.init_db()
    sqlhelper.delete({'name':'2'})
    # sqlhelper.insert({'name':'2','data_momoid':1,'number':2,'searc_count':3,'update_time':time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())})
    items= sqlhelper.select(None,{'name':'2'})
    for item in items:
     print(item)

